const net = require('net')
const express = require('express')
const WebSocket = require('ws')
const cors = require('cors')
const os = require('os')

const app = express()
app.use(cors())

const httpServer = require('http').createServer(app)
const wss = new WebSocket.Server({ server: httpServer })

let latestData = {
  deviceId: null, // 设备ID
  chipTemperature: 0, // 芯片温度
  temperature: 0, // 环境温度
  humidity: 0, // 环境湿度
  timestamp: new Date(),
  status: 'waiting', // waiting, connected, disconnected, error
}

/**
 * 获取所有本机内网 IPv4 地址
 */
function getLocalIPAddresses() {
  const interfaces = os.networkInterfaces()
  const addresses = []

  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name]) {
      if (iface.family === 'IPv4' && !iface.internal) {
        if (!/vmware|virtual|vbox|loopback|docker/i.test(name)) {
          addresses.push({ name, address: iface.address })
        }
      }
    }
  }

  if (addresses.length === 0) return { list: [{ name: '无可用网卡', address: '127.0.0.1' }], preferred: '127.0.0.1' }

  // 优先选择名称中包含 Wi-Fi 或 WLAN 的网卡
  const preferred = addresses.find((ip) => /wi-?fi|wlan/i.test(ip.name))?.address || addresses[0].address

  return { list: addresses, preferred }
}

/**
 * TCP 服务器：处理传感器连接
 */
const tcpServer = net.createServer((socket) => {
  console.log('传感器已连接:', socket.remoteAddress)
  latestData.status = 'connected'

  socket.on('data', (data) => {
    try {
      const dataStr = data.toString().trim()
      console.log('收到数据:', dataStr)

      let parsedData
      // 优先解析 JSON 格式
      if (dataStr.startsWith('{')) {
        parsedData = JSON.parse(dataStr)
      } else if (dataStr.includes(',')) {
        // 支持简单逗号分隔格式，如 "25.5,60"
        const [t, h] = dataStr.split(',')
        parsedData = { temperature: parseFloat(t), humidity: parseFloat(h) }
      } else {
        console.log('未知数据格式:', dataStr)
        return
      }

      // 适配你传感器的 JSON 格式
      if (parsedData.status) {
        const s = parsedData.status
        latestData = {
          deviceId: s.device_id,
          chipTemperature: parseFloat(s.chip_temperature),
          temperature: parseFloat(s.env_temperature),
          humidity: parseFloat(s.env_humidity),
          timestamp: new Date(s.date_time),
          status: 'connected',
        }
      } else {
        // 兼容普通格式
        latestData = {
          temperature: parsedData.temperature || parsedData.temp,
          humidity: parsedData.humidity || parsedData.humi,
          timestamp: new Date(),
          status: 'connected',
        }
      }

      // 广播给 WebSocket 客户端
      broadcastToClients(latestData)
    } catch (error) {
      console.error('数据解析错误:', error)
    }
  })

  // 传感器断开连接
  socket.on('end', () => {
    console.log('传感器断开连接')
    latestData.status = 'disconnected'
    broadcastToClients(latestData)
  })

  // 连接错误
  socket.on('error', (err) => {
    console.error('Socket错误:', err)
    latestData.status = 'error'
  })
})

/**
 * WebSocket 服务器
 */
wss.on('connection', (ws) => {
  console.log('前端 WebSocket 已连接')
    // 初次连接立即发送当前数据
  ws.send(JSON.stringify(latestData))
  ws.on('close', () => console.log('前端 WebSocket 断开'))
})

/**
 * 广播数据到所有 WebSocket 客户端
 * @param {Object} data - 要广播的数据
 */
function broadcastToClients(data) {
  const message = JSON.stringify(data)
  wss.clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(message)
    }
  })
}

/**
 * 获取最新的传感器数据
 */
app.get('/api/latest', (req, res) => {
  res.json(latestData)
})

/**
 * 启动 TCP 和 HTTP 服务
 */
const TCP_PORT = 8888
const HTTP_PORT = 3000

const { list: ipList, preferred } = getLocalIPAddresses()

tcpServer.listen(TCP_PORT, '0.0.0.0', () => {
  console.log(`\n✅ TCP 服务器运行在端口 ${TCP_PORT}`)
  console.log('请在传感器上配置以下任意内网地址：')
  ipList.forEach((ip) => {
    console.log(`  👉 SERVER ADDRESS = ${ip.address}, SERVER PORT = ${TCP_PORT} (${ip.name})`)
  })
  console.log(`\n⭐ 推荐使用地址: ${preferred}\n`)
})

httpServer.listen(HTTP_PORT, () => {
  console.log(`🌐 HTTP + WebSocket 服务器运行在端口 ${HTTP_PORT}`)
  ipList.forEach((ip) => {
    console.log(`  🔗 前端访问地址: http://${ip.address}:${HTTP_PORT}`)
  })
  console.log(`\n⭐ 推荐使用地址: http://${preferred}:${HTTP_PORT}\n`)
})
